<?php

declare (strict_types=1);

namespace app\admin\controller;
use app\common\controller\Backend;
use think\facade\Db;
use app\admin\model\UserRole as UserRoleModel;
use app\admin\model\Menu as MenuModel;


class UserRole extends Backend
{
    public function initialize() {
        parent::initialize();
        $this->_mod  = new \app\admin\model\UserRole();
    }


    public function index(){
        $userRole_mod = new UserRoleModel();
        $list = $userRole_mod->select();
        return view('index',['list'=>$list]);
    }


    public function auth()
    {
        $menu_mod = new MenuModel();
        $auth_mod = Db::name('admin_auth');
        if (isset($_POST['dosubmit'])) {
            $id = intval($_POST['id']);
            //清空权限
            $auth_mod->where(array('role_id'=>$id))->delete();
            if (is_array($_POST['menu_id']) && count($_POST['menu_id']) > 0) {
                foreach ($_POST['menu_id'] as $menu_id) {
                    $auth_mod->insert(array(
                        'role_id' => $id,
                        'menu_id' => $menu_id
                    ));
                }
            }
            return success(1,'操作成功','','add');
        } else {
            $id = request()->param('id');
            $list = $menu_mod->getTree(0);
            //获取被操作角色权限
            $role_data = $auth_mod->where('role_id',$id)->select()->toArray();
            $priv_ids = array();
            foreach ($role_data as $val) {
                $priv_ids[] = $val['menu_id'];
            }
            return view('auth',['id'=>$id,'list'=>$list,'role_data'=>$priv_ids]);
        }
    }


//    public function add(){
//        $role= Db::name('user_role')->where(array('status'=>1))->select();
//        return view('edit',['role'=>$role]);
//    }


}